import React, { useEffect, useState, useMemo } from "react";
import TitleConent from "../../../TitleComponents/index";
import { Tabs } from "antd-mobile";
import { sleep } from "antd-mobile/es/utils/sleep";
import "./index.css";
import { useAppDispatch, useAppSelector } from "../../../../store/index";
import {
  clearList,
  getInformationList,
  getInformationNav,
  resetPayloadLength
} from "../../../../store/sliceReducer/HomeSliceReducer";
import { useNavigate } from "react-router-dom";
import VirtualList from "../VirtualList/index";
import { Toast } from "antd-mobile";

const Index: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [tab4value, setTab4value] = useState<string>("1");
  const { informaitionNavs, informaitionList, lastPayloadLength } =
    useAppSelector((state) => state.home);
  const [hasMore, setHasMore] = useState(true);
  const [page, setPage] = useState(1);
  const [lastResponseLength, setLastResponseLength] = useState(0);

  // 计算容器高度：减去顶部58px和底部70px
  const containerHeight = useMemo(() => {
    return window.innerHeight - 58 - 70 - 40;
  }, []);

  // 动态计算每个资讯项的高度
  const getItemHeight = (item: any) => {
    const imageUrl = item.thumbnail || "";
    const imgLength = imageUrl.split(";");

    if (imgLength.length >= 3) {
      return 176; // 三图布局高度
    } else {
      return 157; // 单图布局高度
    }
  };

  // 计算第一次请求的数量：基于可视区域高度和平均项目高度
  const getInitialCount = useMemo(() => {
    const averageItemHeight = (176 + 157) / 2; // 平均高度
    const visibleCount = Math.ceil(containerHeight / averageItemHeight);
    const overscanCount = 2; // 预加载数量
    return visibleCount + overscanCount;
  }, [containerHeight]);

  // 修复：使用函数式更新，避免直接修改 state
  const [InformationParams, setInformationParams] = useState({
    plateId: "1",
    page: 1,
    count: getInitialCount,
  });
 

  useEffect(() => {
    // 资讯分类导航
    dispatch(getInformationNav());
    // // 重置payload长度
    // dispatch(resetPayloadLength());
  }, [dispatch]);

  // 监听payload长度变化，判断是否还有更多数据
  useEffect(() => {
    console.log("每次收到的数据:", lastPayloadLength);
    if (lastPayloadLength > 0 && lastPayloadLength < getInitialCount) {
      Toast.show({
        icon: "success",
        content: "亲，到底啦",
        duration: 1000,
        afterClose: () => {
          setHasMore(false);
        },
      });
    }
    return () => {
      dispatch(resetPayloadLength());
    };
  }, [lastPayloadLength, getInitialCount]);

  useEffect(() => {
    // 修复：重置分页状态
    setPage(1);
    setHasMore(true);
    dispatch(clearList());

    // 修复：正确更新请求参数
    setInformationParams((prev) => ({
      ...prev,
      plateId: tab4value,
      page: 1,
    }));

    // 修复：使用新的参数发起请求
    dispatch(
      getInformationList({
        plateId: tab4value,
        page: 1,
        count: getInitialCount,
      })
    );
  }, [tab4value, dispatch, getInitialCount]);

  const tabsChange = (value: string) => {
    setTab4value(value);
  };

  // 修复：改进加载更多逻辑
  const loadMore = async () => {
    if (!hasMore) return;

    const nextPage = page + 1;
    setPage(nextPage);

    // 记录当前数据长度
    const currentLength = informaitionList.length;
    setLastResponseLength(0); // 重置

    // 修复：使用新的参数发起请求
    const newParams = {
      plateId: tab4value,
      page: nextPage,
      count: getInitialCount,
    };

    dispatch(getInformationList(newParams));
  };

  // 渲染单个资讯项
  const renderInformationItem = (item: any, index: number) => {
    const imageUrl = item.thumbnail || "";
    const imgLength = imageUrl.split(";");

    if (imgLength.length >= 3) {
      return (
        <div
          className="contenTwo"
          onClick={() => navigate(`/imdetail/` + item.id)}
        >
          <div className="text_box">
            <div className="bot">
              <span>{item.title}</span>
              <span className="info">飞飞营养师</span>
            </div>
          </div>
          <div className="img_box">
            {imgLength.map((v: string) => {
              return <img key={v} src={v} alt="" />;
            })}
          </div>
        </div>
      );
    } else {
      return (
        <div
          className="contentOne"
          onClick={() => navigate(`/imdetail/` + item.id)}
        >
          <img src={item.thumbnail} alt="" />
          <div className="text_box">
            <div className="top">{item.title}</div>
            <div className="bot">
              <span className="info">飞飞营养师</span>
              <span className="time">10分钟前</span>
            </div>
          </div>
        </div>
      );
    }
  };

  // 修复：改进条件渲染逻辑
  const renderContent = (navId: string) => {
    if (tab4value !== String(navId)) return null;

    return (
      <>
        {/* 使用虚拟列表渲染资讯项，内置无限滚动 */}
        <VirtualList
          // 数据
          data={informaitionList}
          // 获取每个item的高度
          getItemHeight={getItemHeight}
          // 容器高度
          containerHeight={containerHeight}
          // 渲染每个item
          renderItem={renderInformationItem}
          // 加载更多
          loadMore={loadMore}
          // 是否还有更多数据
          hasMore={hasMore}
          // 距离内容底部200px时触发加载更多
          threshold={200}
        />
      </>
    );
  };

  return (
    <div>
      <TitleConent text={"健康咨询"} />

      <div className="information_content">
        <Tabs
          activeKey={tab4value}
          defaultActiveKey={tab4value}
          onChange={(value) => tabsChange(value)}
        >
          {informaitionNavs.map((v) => (
            <Tabs.Tab key={v.id} title={v.name}>
              {renderContent(String(v.id))}
            </Tabs.Tab>
          ))}
        </Tabs>
      </div>
    </div>
  );
};

export default Index;
